package com.sfc.spiderweb.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * @title: OssUtil
 * @projectName archives
 * @description:
 * @date 2019/6/2516:00
 */

@Component
public class OssUtil {

    public static String endpoint;
    public static String accessKeyId;
    public static String accessKeySecret;
    public static String bucketName;

    @Value("${spider.alioss.endpoint}")
    public String setEndpoint(String endpoint) {
        return OssUtil.endpoint = endpoint;
    }

    @Value("${spider.alioss.accessKeyId}")
    public String setAccessKeyId(String accessKeyId) {
        return OssUtil.accessKeyId = accessKeyId;
    }

    @Value("${spider.alioss.accessKeySecret}")
    public String setAccessKeySecret(String accessKeySecret) {
        return OssUtil.accessKeySecret = accessKeySecret;
    }

    @Value("${spider.alioss.bucketName}")
    public String setBucketName(String bucketName) {
        return OssUtil.bucketName = bucketName;
    }

    private static class OSSClientHolder {
        private static final OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        private OSSClientHolder() {
        }

    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String ossPath) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = OSSClientHolder.ossClient.generatePresignedUrl(bucketName, ossPath, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 上传文件到OSS
     *
     * @param file
     * @param ossPath
     */
    public static void uploadFileToOss(File file, String ossPath) {
        OSSClientHolder.ossClient.putObject(bucketName, ossPath, file);
    }

    /**
     * 下载OSS文件到本地
     *
     * @param file
     * @param ossPath
     */
    public static void downloadFileToLocal(String ossPath, String localPath) throws Exception {
        File file = FileUtil.createFile(localPath);
        OSSClientHolder.ossClient.getObject(new GetObjectRequest(bucketName, ossPath), file);
    }


/*     @Test
    public void download(){
        this.setAccessKeyId("LTAIe8n0hX4dmduK");
        this.setAccessKeySecret("mAYUJiQANUx2jMbTlClONovrFOo0tz");
        this.setEndpoint("oss-cn-beijing.aliyuncs.com");
        this.setBucketName("sfcdocbackup");
        OSSClientHolder.ossClient.getObject(new GetObjectRequest(bucketName, "archives\\143\\应聘登记表"), new File("C:\\Users\\szpc-01\\Desktop\\aa"));
    }*/


}
